package com.wwdeng.smart

import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.wwdeng.smart.app.AppData
import com.wwdeng.smart.base.BaseAct
import com.wwdeng.smart.databinding.UiMainBinding
import com.wwdeng.smart.video.LocalVideoAct
import com.wwdeng.smart.video.VideoPreviewAct
import org.json.JSONObject

/**
 * SmartCamera
 * @Author wwdeng
 * @CreateTime: 2024/9/19 19:18
 * @Annotation：
 */
class MainAct: BaseAct() {
    lateinit var binding: UiMainBinding

    override fun getRootView(): View {
        binding = UiMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView() {
    }

    override fun initListener() {
        binding.btnGetXP2P.setOnClickListener {
            getDeviceXP2PInfoAction()
        }

        binding.btnPreview.setOnClickListener {
            if (binding.textXP2PInfo.text.toString().isEmpty()){
                Toast.makeText(this,"xp2pInfo is empty",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            VideoPreviewAct.startPreviewActivity(this,"","","")
        }

        binding.btnLocal.setOnClickListener {
            if (binding.textXP2PInfo.text.toString().isEmpty()){
                Toast.makeText(this,"xp2pInfo is empty",Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }
            startActivity(Intent(this,LocalVideoAct::class.java))
        }
    }

    override fun initData() {
        AppData.accessId = binding.editAccessId.text.toString().trim()
        AppData.accessToken = binding.editAccessToken.text.toString().trim()
        AppData.productId = binding.editProductId.text.toString().trim()
        AppData.deviceName = binding.editDeviceName.text.toString().trim()
    }

    private fun getDeviceXP2PInfoAction(){
        val pId = AppData.productId
        val deviceName = AppData.deviceName
        val httpUrl = "http://api.tcipc.smilesmartai.com/api/device/attribute?product_id=$pId&device_name=$deviceName"
        OkGo.get<String>(httpUrl)
            .execute(object : StringCallback() {
                override fun onSuccess(response: Response<String?>) {
                    Log.e("TAG", "---------------->"+ response.body())
                    val data = response.body()?.let { JSONObject(it) }
                    if (data != null && data.optInt("code") == 200){
                        val xp2p_info = data.optJSONObject("data")!!.optJSONObject("_sys_xp2p_info")!!.optString("Value")
                        AppData.xp2pInfo = xp2p_info
                        binding.textXP2PInfo.text = xp2p_info
                    }
                }
                override fun onError(response: Response<String?>?) {
                }

                override fun onFinish() {
                }
            })
    }
}